package com.atguigu.yygh.hosp.receiver;

import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.rabbit.RabbitService;
import com.atguigu.yygh.rabbit.constant.MqConst;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class ScheduleReceiver {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RabbitService rabbitService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
            key = {MqConst.ROUTING_ORDER}
    ))
    public void receiver(OrderMqVo orderMqVo, Message message, Channel channel) {
        //根据有无数量判断是生成订单更新还是退款更新
        if (null != orderMqVo.getAvailableNumber()) {
            //获取发送端传过来的排班id
            String scheduleId = orderMqVo.getScheduleId();
            //根据排班id查询
            Schedule schedule = scheduleService.getScheduleById(scheduleId);
            //设置更新值
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            schedule.setReservedNumber(orderMqVo.getReservedNumber());
            //调用方法更新
            scheduleService.updateScheduleMq(schedule);
        } else {//平台排班可预约数加1
            Schedule schedule = scheduleService.getScheduleById(orderMqVo.getScheduleId());
            Integer availableNumber = schedule.getAvailableNumber();
            schedule.setAvailableNumber(availableNumber + 1);
            scheduleService.updateScheduleMq(schedule);
        }
        //更新排班之后发送短信给msm模块以通知就诊人
        MsmVo msmVo = orderMqVo.getMsmVo();
        String phone = msmVo.getPhone();
        if (!StringUtils.isEmpty(phone)) {
            //发送mq消息
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }

    }
}
